package com.enjoychain.www.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.enjoychain.www.security.constant.BusinessTaskType;
import com.enjoychain.www.security.entity.BasicFile;
import com.enjoychain.www.security.mapper.BasicFileMapper;
import com.enjoychain.www.security.service.IBasicFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 基础文件信息表 服务实现类
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-29
 */
@Service
public class BasicFileServiceImpl extends ServiceImpl<BasicFileMapper, BasicFile> implements IBasicFileService {

    QueryWrapper<BasicFile> buildQueryWrapperWithTypeAndId(BusinessTaskType type, String id){
        QueryWrapper<BasicFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("busi_type",type);
        queryWrapper.eq("connect_id",id);
        return queryWrapper;
    }

    @Override
    public List<BasicFile> getListByTypeAndId(BusinessTaskType type, String id) {
        return list(buildQueryWrapperWithTypeAndId(type,id));
    }

    @Override
    public boolean removeFileById(int id) throws IOException {
        BasicFile file = baseMapper.selectById(id);
        if (file != null) {
            File temp = new File(file.getPath());
            if (temp.exists()) {
                FileUtils.forceDelete(new File(file.getPath()));
            }
        }
        return this.removeById(id);
    }


    @Override
    public boolean removeFileByConnectIdAndBusiType(BusinessTaskType businessType, String connectId)  {
        List<BasicFile> fileList = getListByTypeAndId(businessType, connectId);
        for (BasicFile file: fileList){
            if (file != null) {
                File temp = new File(file.getPath());
                if (temp.exists()) {
                    try {
                        FileUtils.forceDelete(new File(file.getPath()));
                    } catch (IOException e) {
                        log.error("DELETE FILE ERROR",e);
                    }
                }
            }
            this.removeById(file);
        }
        return true;
    }

    @Override
    public BasicFile getSingleByTypeAndId(BusinessTaskType taskType, String connectId) {
        QueryWrapper<BasicFile> queryWrapper = buildQueryWrapperWithTypeAndId(taskType,connectId);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }
}
